<template>
  <div class="role">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col :span="24"
          ><el-button type="primary" @click="addRole"
            >添加角色</el-button
          ></el-col
        >
      </el-row>
      <el-table :data="roleList">
        <!--  展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              :gutter="20"
              v-for="item1 in scope.row.children"
              :key="item1.id"
              class="bord1 "
            >
              <el-col :span="6" class="auth1"
                ><el-tag closable @close="delRight(scope.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="17">
                <el-row
                  v-for="item2 in item1.children"
                  :key="item2.id"
                  class="bord2"
                  :gutter="20"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="delRight(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="delRight(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    ></el-col
                  >
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"> </el-table-column>
        <el-table-column label="角色名称" prop="roleName"> </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
        <el-table-column label="操作" width="360">
          <template v-slot="scope">
            <!-- 编辑 -->

            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="getRoleInfo(scope.row.id)"
              >编辑</el-button
            >
            <!--  删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="isDelete(scope.row.id)"
              >删除</el-button
            >
            <!--   分配角色 -->
            <el-button
              type="warning"
              icon="el-icon-s-custom"
              size="mini"
              @click="showDistribute(scope.row)"
              >分派权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色 -->
      <el-dialog
        title="添加角色"
        :visible.sync="showAddDialog"
        width="30%"
        @close="closeAdd"
      >
        <el-form
          :model="addRoleForm"
          :rules="addRoleRules"
          ref="addFormRef"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="showAddDialog = false">取 消</el-button>
        <el-button type="primary" @click="preAdd">确 定</el-button>
      </el-dialog>
      <!--   编辑角色 -->
      <el-dialog
        title="提示"
        :visible.sync="showEdit"
        width="30%"
        @close="closeEdit"
      >
        <el-form
          :rules="editFormRules"
          ref="editForm"
          :model="editForm"
          label-width="80px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="showEdit = false">取 消</el-button>
        <el-button type="primary" @click="putEditRole">确 定</el-button>
      </el-dialog>
      <!-- 分配权限 -->
      <el-dialog
        title="分配权限"
        :visible.sync="distributeDialog"
        @close="closeDistriDialog"
      >
        <el-tree
          :data="rightsTree"
          :props="treeProps"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="defkeys"
          ref="treeRef"
        ></el-tree>
        <el-button @click="distributeDialog = false">取 消</el-button>
        <el-button type="primary" @click="distributeRight"
          >确 定</el-button
        ></el-dialog
      >
    </el-card>
  </div>
</template>

<script>
export default {
  name: "",
  components: {},
  data() {
    return {
      roleList: [],
      showAddDialog: false,
      showEdit: false,
      distributeDialog: false,
      addRoleForm: {
        roleName: "王五",
        roleDesc: "测试1",
      },
      addRoleRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 1, max: 5, message: "长度在 1 到 5 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
      },
      editForm: {},
      editFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 1, max: 5, message: "长度在 1 到 5 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
      },
      rightsTree: [],
      treeProps: {
        children: "children",
        label: "authName",
      },
      //默认树形列表选中的节点id
      defkeys: [],
      //当前即将分配权限角色的id
      rolesId: 0,
    };
  },
  created() {
    this.getRoles();
  },
  methods: {
    async getRoles() {
      const { data: res } = await this.$request({
        url: "roles",
      });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.roleList = res.data;
    },
    addRole() {
      this.showAddDialog = true;
    },
    closeAdd() {
      this.$refs.addFormRef.resetFields();
    },
    preAdd() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$request({
          url: "roles",
          method: "post",
          data: this.addRoleForm,
        });
        if (res.meta.status !== 201) {
          this.$message.error("创建用户失败");
          this.showAddDialog = "false";
        }
        this.$message.success("创建用户成功");
        this.getRoles();
        this.showAddDialog = false;
      });
    },
    async getRoleInfo(id) {
      this.showEdit = true;
      const { data: res } = await this.$request({
        url: "roles/" + id,
      });
      console.log(res);
      if (res.meta.status !== 200) {
        return;
      }
      this.editForm = res.data;
    },
    closeEdit() {
      this.$refs.editForm.resetFields();
    },
    //编辑角色
    async putEditRole() {
      console.log(this.editForm);
      const { data: res } = await this.$request({
        url: "roles/" + this.editForm.roleId,
        method: "put",
        data: {
          /*     id: this.editForm.roleId, */
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc,
        },
      });

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.showEdit = false;
      this.getRoles();
      this.$message.success("修改成功");
    },
    //删除角色
    async isDelete(id) {
      const res = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => {
        this.$message({
          type: "info",
          message: "已取消删除",
        });
        return err;
      });
      if (res === "confirm") {
        const { data: res } = await this.$request({
          url: "roles/" + id,
          method: "delete",
        });
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("删除失败");
        }
        this.getRoles();
        this.$message.success("删除成功");
      }
    },
    //展开列中删除权限
    async delRight(roles, rightId) {
      const res = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(res);
      if (res !== "confirm") {
        return this.$message.info("取消删除");
      }
      const { data } = await this.$request({
        url: `roles/${roles.id}/rights/${rightId}`,
        method: "delete",
      });
      console.log(data);
      if (data.meta.status !== 200) {
        return this.$message.error(data.meta.msg);
      }
      roles.children = data.data; /* this.getRoles();会重新刷新，关闭下拉权限 */
      this.$message.success("删除成功");
    },
    //显示权限树对话框
    async showDistribute(roles) {
      this.rolesId = roles.id;
      //  console.log(roles);
      //请求所有权限
      const { data: res } = await this.$request({
        url: "rights/tree",
        method: "get",
      });
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.rightsTree = res.data;
      this.getdefKeys(roles, this.defkeys);
      this.distributeDialog = true;
    },
    //通过递归得到选中三级权限的id
    getdefKeys(node, arr) {
      /* node判断是否是三级节点，没有children */
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getdefKeys(item, arr);
      });
    },
    //对话框关闭，清空数据
    closeDistriDialog() {
      this.defkeys = [];
    },

    //为角色分配权限
    async distributeRight() {
      //拿到所有全选和半选的权限id合并数组
      let keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];

      const keystr = keys.join(",");

      const { data: res } = await this.$request({
        url: "roles/" + this.rolesId + "/rights",
        method: "post",
        data: {
          rids: keystr,
        },
      });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
      this.getRoles();
      this.distributeDialog = false;
    },
  },
};
</script>
<style scoped>
.el-card {
  margin-top: 30px;
}
.bord1 {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ececec;
}
.bord2 {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ececec;
  margin: 6px;
}
.auth1 {
  margin: 10px;
}
</style>
